#!/bin/bash

# 编译的CPU核心数
coreNum=1
if [ $# -ne 0 ]; then
  coreNum=$1
fi

workDir=/opt
rootPath=$(dirname "$(readlink -f "$0")")

# 定义资源路径和协议路径
resourcePath="$rootPath/code/resource"
protocolPath="$rootPath/code/zeroplusmq/network/protocol"
testsPath="$rootPath/code/tests"

# 定义清理函数
cleanProtoFiles() {
  local path=$1
  echo "Cleaning old *.pb.h and *.pb.cc files in $path..."
  find "$path" -type f \( -name "*.pb.h" -o -name "*.pb.cc" \) -delete
}

# 清理旧文件
cleanProtoFiles "$resourcePath"
cleanProtoFiles "$protocolPath"
cleanProtoFiles "$testsPath"

# 定义生成C++代码的函数
generateCppCode() {
  local path=$1
  echo "Generating C++ code from proto files in $path..."
  while IFS= read -r -d '' protoFile; do
    echo "Generating C++ code for $protoFile..."
    protoc -I=$path --cpp_out=$path "$protoFile"
  done < <(find "$path" -type f -name '*.proto' -print0)
}

# 生成C++代码
generateCppCode "$resourcePath"
generateCppCode "$protocolPath"
generateCppCode "$testsPath"

# 构建项目
echo "Building the project..."
if [ -d "$rootPath/zeroplusmq" ]; then
    rm -rf "$rootPath/zeroplusmq"
fi
cmake -S "$rootPath/code/" -B build -D CMAKE_C_COMPILER_LAUNCHER=ccache -D CMAKE_CXX_COMPILER_LAUNCHER=ccache -D CMAKE_INSTALL_PREFIX="$rootPath/zeroplusmq"
cmake --build build --parallel $coreNum
cmake --install build
rm -rf build
cp -r "$rootPath/conf" zeroplusmq
cp -r "$rootPath/docker" zeroplusmq
mkdir -p "$rootPath/zeroplusmq/db"
